package top.eggcode.common.lang;

import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * Title: 加密工具
 * Description: TODO
 * Date: 2021/4/10 9:11
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Component
public class EncryptionUtil {
    public static void main(String[] args) {
        System.out.println(
                hashMd5("QNKCDZO")
        );
    }

    /**
     * 生成密码盐
     *
     * @return 盐值
     */
    public static String randomSolt() {
        //利用UUID生成随机盐
        UUID uuid = UUID.randomUUID();
        //返回a2c64597-232f-4782-ab2d-9dfeb9d76932
        return uuid.toString().replace("-", "");
    }

    /**
     * 哈希计算，MD5
     *
     * @param text 普通文本
     * @return 字符串
     */
    public static String hashMd5(String text) {
        try {
            //实例化MessageDigest的MD5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //通过digest方法返回哈希计算后的字节数组
            byte[] bytes = md.digest(text.getBytes(StandardCharsets.UTF_8));
            //将字节数组转换为16进制字符串并返回
            return convertToHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException("哈希-MD5 计算失败", e);
        }
    }

    /**
     * 、获得16进制字符串
     *
     * @param bytes 数组
     * @return 16进制字符串
     */
    private static String convertToHex(byte[] bytes) {
        final char[] hexNumbers = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            ret.append(hexNumbers[(aByte >> 4) & 0x0f]);
            ret.append(hexNumbers[aByte & 0x0f]);
        }
        return ret.toString();
    }

}
